package com.fortune.rainshine.controller;

import com.fortune.rainshine.feign.service.PurchaseFeign;
import com.fortune.rainshine.feign.service.ShopFeign;
import com.fortune.rainshine.feign.system.UserFeign;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.service.OrderModel;
import com.fortune.rainshinecommon.model.system.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("purchaseController")
public class PurchaseController {
    private static final Logger logger = LoggerFactory.getLogger(PurchaseController.class);

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private PurchaseFeign purchaseFeign;

    @Autowired
    private ShopFeign shopFeign;

    @RequestMapping("/order")
    @ResponseBody
    public MsgModel order(@RequestBody OrderModel model){
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        String userId = request.getHeader("userId");
//        if(model.getUserId() == null){
//            return new MsgModel("登录用户异常", ResultCode.FAILURE);
//        }
        if(model.getShopId() == null){
            return new MsgModel("商铺参数异常", ResultCode.FAILURE);
        }
        ShopModel shopModel = shopFeign.getShopByShopId(model.getShopId());
        if(shopModel == null){
            return new MsgModel("商铺信息异常", ResultCode.FAILURE);
        }
        if(Integer.valueOf(userId) != shopModel.getManagerId()){
            return new MsgModel("无操作权限", ResultCode.FAILURE);
        }
        try {
            User user = userFeign.getUserById(Integer.valueOf(userId));
//            User user = userFeign.getUserById(model.getUserId());
//            if(user == null){
//                return new MsgModel( "此用户不存在", ResultCode.FAILURE);
//            }
//            Integer roleId = userFeign.getRoleIdByUserId(model.getUserId());
            Integer roleId = userFeign.getRoleIdByUserId(Integer.valueOf(userId));
            user.setRoleId(roleId);
            model.setUser(user);
            return purchaseFeign.order(model);
        }catch (Exception e){
            logger.error("PurchaseController order ====> {}", e);
            return new MsgModel("采购订单异常", ResultCode.FAILURE);
        }
    }
}
